package com.x.erp.controller;

import java.math.BigDecimal;
import java.util.*;


import com.x.erp.model.*;
import com.x.erp.util.Constant;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.x.erp.rpc.CarRpcService;
import com.x.erp.rpc.CityRpcService;
import com.x.erp.rpc.ContractRegionRpcService;
import com.x.erp.rpc.ModelRpcService;
import com.x.erp.rpc.ProvinceRpcService;
import com.x.erp.rpc.RegionRpcService;
import com.x.erp.rpc.SaleBillRpcService;
import com.x.erp.rpc.ShopRpcService;
import com.x.erp.rpc.UserRpcService;
import com.x.erp.util.ConstantState;
import com.x.framework.controller.BaseController;
import com.x.framework.controller.ResultCode;
import com.x.framework.controller.ResultModel;

import javax.servlet.http.HttpServletRequest;

/**
 * 市场数据信息api
 */
@RestController
@RequestMapping("/public/open/market")
public class DataApiController extends BaseController{

	private Logger logger = LogManager.getLogger(this.getClass());

	@Reference
	private SaleBillRpcService saleBillRpcService;//销售单据信息服务

	@Reference
	private ShopRpcService shopRpcService;//商铺信息服务

	@Reference
	private RegionRpcService regionRpcService;//区域信息服务

	@Reference
	private ContractRegionRpcService contractRegionRpcService;//区域合同信息服务

	@Reference
	private CarRpcService carRpcService;//车辆信息服务

	@Reference
	private ModelRpcService modelRpcService;//车型服务

	@Reference
	private ProvinceRpcService provinceRpcService;//省信息服务

	@Reference
	private CityRpcService cityRpcService;//市信息服务

	@Reference
	private UserRpcService userRpcService;// 用户服务

	@Autowired
	private FastFileStorageClient fdfsClient;//文件服务

	/**
	 * 插入销售信息
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/insertSaleBill", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel insertSaleBill(SaleBill saleBill) {
		if(saleBill == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "单据信息不能为空！");
		}
		if(saleBill.getBillDate() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "开票日期不能为空！");
		}
		if(StringUtils.isEmpty(saleBill.getBillCode())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "发票代码不能为空！");
		}
		if(StringUtils.isEmpty(saleBill.getBillNo())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "发票号码不能为空！");
		}
		if(saleBill.getBillPrice() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "发票金额不能为空！");
		}else {
			BigDecimal zero = BigDecimal.valueOf(0);
			if (saleBill.getBillPrice().compareTo(zero) <= 0) {
				return new ResultModel(ResultCode.RESULT_FAIL, "发票金额不能小于等于0！");
			}
		}
		if(StringUtils.isEmpty(saleBill.getBillCarMark())) { 
			return new ResultModel(ResultCode.RESULT_FAIL, "厂牌不能为空！");
		}
		if(StringUtils.isEmpty(saleBill.getBillCarVin())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车架号不能为空！");
		}
		if(StringUtils.isEmpty(saleBill.getBillCarEngineNo())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "发动机号不能为空！");
		}
		if(StringUtils.isEmpty(saleBill.getBillCarName())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆名称不能为空！");
		}
		if(StringUtils.isEmpty(saleBill.getBillCarPlateHead()) 
				|| StringUtils.isEmpty(saleBill.getBillCarPlateMiddle()) 
				|| StringUtils.isEmpty(saleBill.getBillCarPlateCode())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆号牌不能为空！");
		}
		if(saleBill.getCarTypeId() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆类型不能为空！");
		}
		if(saleBill.getBrandId() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "品牌不能为空！");
		}
		if(saleBill.getSeriesId() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车系不能为空！");
		}
		if(saleBill.getModelId() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车型不能为空！");
		}
		if(StringUtils.isEmpty(saleBill.getMarketId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "市场不能为空！");
		}
		if(StringUtils.isEmpty(saleBill.getShopId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "店铺不能为空！");
		}
//		if(StringUtils.isEmpty(saleBill.getUserId())) {
//			return new ResultModel(ResultCode.RESULT_FAIL, "用户信息不能为空！");
//		}
		//根据市场提供的marketShopId查询商铺信息
		Shop shop = new Shop();
		shop.setShopMappingId(saleBill.getShopId());
		List<Shop> shops = shopRpcService.selectShopList(shop);
		if(shops == null || shops.size() == 0) {
			return new ResultModel(ResultCode.RESULT_FAIL, "商铺ID错误！");
		}
		shop = shops.get(0);
		saleBill.setShopId(shop.getShopId());//查询到的shopId
		//查询用户信息
		User user = new User();
		user.setShopId(shop.getShopId());
		user.setUserType(40);
		List<User> users = userRpcService.selectUserList(user);
		if(users != null && users.size() > 0) {
			user = users.get(0);
			saleBill.setUserId(user.getUserId());
		}else {
			saleBill.setUserId("0");
		}
		//根据市场的车型ID查询车型信息
		Model model = new Model();
		model.setModelId(saleBill.getModelId());
		model = modelRpcService.selectModelMapping(model, saleBill.getMarketId());
		if(model == null) {
			saleBill.setModelId(0);
			saleBill.setSeriesId(0);
			saleBill.setBrandId(0);
		}else {
			saleBill.setModelId(model.getModelId());
			saleBill.setSeriesId(model.getSeriesId());
			saleBill.setBrandId(model.getSeries().getBrandId());
		}
		saleBill.setBillCreateTime(new Date());
		saleBillRpcService.insertSaleBill(saleBill);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "插入成功");
	}

	/**
	 * 新增商铺信息
	 * @param shop
	 * @return
	 */
	@RequestMapping(value = "/insertShopInfo", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel insertShopInfo(Shop shop, User user) {
		if(shop == null || user == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "商户信息不能为空！");
		}
		if(StringUtils.isEmpty(user.getUserName())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "用户姓名不能为空！");
		}
		if(StringUtils.isEmpty(user.getUserMobile())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "用户联系方式不能为空！");
		}
		if(StringUtils.isEmpty(shop.getMarketId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "市场ID不能为空！");
		}
		if(StringUtils.isEmpty(shop.getShopName())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "商户名称不能为空！");
		}
		if(StringUtils.isEmpty(shop.getShopMobile())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "商户联系方式不能为空！");
		}
		if(StringUtils.isEmpty(shop.getShopMappingId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "商户ID不能为空！");
		}
		shop.setShopId(null);
		shop.setShopState(1);
		Date cDate = new Date();
		shop.setShopCreateTime(cDate);
		shop.setShopUpdateTime(cDate);
		user.setUserType(40);
		user.setUserState(1);
		user.setShop(shop);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "插入成功", shopRpcService.insertShopUser(user));
	}

	/**
	 * 新增区域信息
	 * @param region
	 * @return
	 */
	@RequestMapping(value = "/insertRotation", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel insertRotation(Region region) {
		if(region == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "区域信息不能为空！");
		}
		if(region.getRegionType() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "区域类型不能为空！（1：按面积、2：按车位）");
		}
		if(StringUtils.isEmpty(region.getRegionName())){
			return new ResultModel(ResultCode.RESULT_FAIL, "区域名称不能为空！");
		}
		if(region.getRegionRentFee() == null){
			return new ResultModel(ResultCode.RESULT_FAIL, "租金不能为空！");
		}
		if(StringUtils.isEmpty(region.getMarketId())){
			return new ResultModel(ResultCode.RESULT_FAIL, "市场ID不能为空！");
		}
		region.setRegionState(1);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "插入成功", regionRpcService.insertRegion(region));
	}

	/**
	 * 新增区域合同信息
	 * @param contract
	 * @param contractRegion
	 * @return
	 */
	@RequestMapping(value = "/insertContractRegion", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel insertContractRegion(Contract contract, ContractRegion contractRegion) {
		if(contract == null || contractRegion == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "区域合同信息不能为空！");
		}
		if(contract.getContractStartDate() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "合同开始时间不能为空！");
		}
		if(contract.getContractEndingDate() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "合同结束时间不能为空！");
		}
		if(contract.getContractState() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "合同状态不能为空！（1-未生效，2-执行中，3-结束，4-意外中止）");
		}
		if(contract.getContractState() == 4 && contract.getContractCrashDate() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "合同意外中止日期不能为空！");
		}
		if(StringUtils.isEmpty(contract.getMarketId())){
			return new ResultModel(ResultCode.RESULT_FAIL, "市场ID不能为空！");
		}
		if(StringUtils.isEmpty(contract.getShopId())){
			return new ResultModel(ResultCode.RESULT_FAIL, "商铺ID不能为空！");
		}
		if(contractRegion.getContractRegionRentCount() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "租用面积或者车位不能为空！");
		}
		if(contractRegion.getContractRegionRentFee() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "租金不能为空！(每月每平米/每个)");
		}
		if(StringUtils.isEmpty(contractRegion.getRegionId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "区域ID不能为空！");
		}
		Date cDate = new Date();
		contractRegion.setContractRegionState(contract.getContractState());
		contractRegion.setContractRegionCrashDate(contract.getContractCrashDate());
		contract.setContractCreateTime(cDate);
		contract.setContractUpdateTime(cDate);
		contractRegion.setContractRegionCreateTime(cDate);
		contractRegion.setContractRegionUpdateTime(cDate);
		contractRegion.setContract(contract);
		contractRegionRpcService.insertContractRegion(contractRegion);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "插入成功！");
	}

	/**
	 * 唐山新增车辆信息
	 * @param car
	 * @param carImageJson
	 * @return
	 */
	@RequestMapping(value = "/insertCarTS", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel insertCarTS(Car car, String carImageJson, String token, HttpServletRequest request) {
		String resource = request.getHeader("resource");
		String ip = getClientIP(request);
		if(!Constant.IP_WHITE_LIST.contains(ip)){
			return new ResultModel(ResultCode.RESULT_FAIL, "该IP无访问权限！");
		}
		if(StringUtils.isEmpty(token) || !token.equals("b50e7a3c8ddec4b881135faf217cace4")){
			return new ResultModel(ResultCode.RESULT_FAIL, "token错误！");
		}
		if(car == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆信息不能为空！");
		}
		if(car.getCarTypeId() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆类型不能为空！");
		}
//		if(car.getBrandId() == null) {
//			return new ResultModel(ResultCode.RESULT_FAIL, "品牌不能为空！");
//		}
//		if(car.getSeriesId() == null) {
//			return new ResultModel(ResultCode.RESULT_FAIL, "车系不能为空！");
//		}
		if(car.getModelId() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车型不能为空！");
		}
		if(StringUtils.isEmpty(car.getMarketId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "市场不能为空！");
		}
		if(StringUtils.isEmpty(car.getShopId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "店铺不能为空！");
		}
//		if(StringUtils.isEmpty(car.getUserId())) {
//			return new ResultModel(ResultCode.RESULT_FAIL, "用户信息不能为空！");
//		}
		if(StringUtils.isEmpty(car.getCarVin()) || car.getCarVin().length() != 17) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车驾号信息不正确（17位）！");
		}
		if(!valiCarVinExist(car.getCarVin(), car.getCarId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车驾号已存在！");
		}
		if(StringUtils.isEmpty(car.getCarOutColor())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆颜色不能为空！");
		}
//		if(StringUtils.isEmpty(car.getSaleUserId())){
//			return new ResultModel(ResultCode.RESULT_FAIL, "销售用户不能为空！");
//		}
		if(StringUtils.isEmpty(car.getRegionId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车场区域不能为空！");
		}
		if(StringUtils.isEmpty(car.getCarTitle())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "宣传标题不能为空！");
		}
		if(car.getCarMileage() == null || car.getCarMileage().compareTo(new BigDecimal(0.0001)) < 0 || car.getCarMileage().compareTo(new BigDecimal(100)) >= 0) {
			return new ResultModel(ResultCode.RESULT_FAIL, "行驶里程数据错误（大于0小于100/万公里）！");
		}
		if(car.getCarRetailPrice() == null || car.getCarRetailPrice().compareTo(new BigDecimal(0)) < 0 || car.getCarRetailPrice().compareTo(new BigDecimal(10000)) >= 0) {
			return new ResultModel(ResultCode.RESULT_FAIL, "请填写正确的零售价（0~9999.99/万元）！");
		}
		if(car.getCarLicenceState() == null){
			return new ResultModel(ResultCode.RESULT_FAIL, "请选择是否上牌");
		}
		//是否上牌（1：已上牌、2：未上牌、3：新车）
		if(car.getCarLicenceState() == 1 && car.getCarLicenceDate() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "请填写上牌日期");
		}else if(car.getCarLicenceDate() != null && car.getCarLicenceDate().after(this.getDate(0))){
			return new ResultModel(ResultCode.RESULT_FAIL, "首次上牌日期不能大于当前日期！");
		}
		if(car.getCarLicenceState() == 1 && car.getCarValidateDate() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "请填写年审日期");
		}
		if(car.getCarLicenceState() == 1 && car.getCarForceInsuranceDate() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "请填写交强险日期");
		}
		Date cDate = this.getDate(0);
		if(car.getCarLicenceDate() == null){
			car.setCarLicenceDate(cDate);
		}
		if(StringUtils.isEmpty(car.getCarGearbox())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "请选择变速箱");
		}
		if(!car.getCarGearbox().equals("自动") && !car.getCarGearbox().equals("手动")){
			return new ResultModel(ResultCode.RESULT_FAIL, "变速箱格式不正确");
		}
		/*if(car.getCarTransferNum() == null || car.getCarTransferNum() < 0 || car.getCarTransferNum() > 99){
			return new ResultModel(ResultCode.RESULT_FAIL, "请填写正确的过户次数（0~99）");
		}*/
		if(StringUtils.isEmpty(car.getCarDisplacement())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "请选择排量");
		}
		if(StringUtils.isEmpty(car.getCarInletModel())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "请选择进气方式");
		}
		if(!car.getCarInletModel().equals("L") && !car.getCarInletModel().equals("T")){
			return new ResultModel(ResultCode.RESULT_FAIL, "进气方式格式不正确");
		}
		if(StringUtils.isEmpty(car.getMarketCarId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "市场车辆ID不能为空！");
		}
		Car temCar = new Car();
		temCar.setMarketCarId(car.getMarketCarId());
		temCar.setMarketId(car.getMarketId());
		temCar.setPageIndex(1);
		temCar.setPageSize(1);
		List<Car> temList = carRpcService.selectCarList(temCar);
		if(temList != null && temList.size() > 0){
			return new ResultModel(ResultCode.RESULT_FAIL, "市场车辆ID已存在！");
		}
		//根据市场提供的marketShopId查询商铺信息
		Shop shop = new Shop();
//		shop.setShopMappingId(car.getShopId());
		shop.setShopId(car.getShopId());
		List<Shop> shops = shopRpcService.selectShopList(shop);
		if(shops == null || shops.size() == 0) {
			return new ResultModel(ResultCode.RESULT_FAIL, "商铺ID错误！");
		}
		Region region = new Region();
		region.setMarketId(car.getMarketId());
		region.setRegionId(car.getRegionId());
		List<Region> regions = regionRpcService.selectRegionList(region);
		if(regions == null || regions.size() == 0) {
			return new ResultModel(ResultCode.RESULT_FAIL, "区域ID错误！");
		}
		//查询用户信息
		User user = new User();
//		user.setShopId(shop.getShopId());
		user.setShopId(car.getShopId());
		user.setUserType(40);
		List<User> users = userRpcService.selectUserList(user);
		if(users != null && users.size() > 0) {
			user = users.get(0);
			car.setUserId(user.getUserId());
			car.setSaleUserId(user.getUserId());
		}else {
			return new ResultModel(ResultCode.RESULT_FAIL, "该商铺尚未添加车商，请添加后再试！");
		}
		//查询车型信息
		Model model = new Model();
		model.setModelId(car.getModelId());
		model = modelRpcService.selectModelMapping(model, car.getMarketId());
		if(model == null || model.getModelId() == 0) {
			return new ResultModel(ResultCode.RESULT_FAIL, "无匹配车型！");
		}else {
			car.setModelId(model.getModelId());
			car.setSeriesId(model.getSeriesId());
			car.setBrandId(model.getSeries().getBrandId());
		}
		car.setCarVin6(car.getCarVin().substring(11, 17));//截取后6位
		//初始化状态值
		car.setCarAuthState(ConstantState.CAR_AUTH_STATE_INITIAL);
		car.setCarSaleState(ConstantState.CAR_SALE_STATE_INITIAL);
		car.setCarStockState(ConstantState.CAR_STOCK_STATE_IN_ING);// 入库中
		car.setCarDetectState(ConstantState.CAR_DETECT_STATE_INITIAL);
		car.setCarOrderState(ConstantState.CAR_ORDER_STATE_INITIAL);
		car.setCarSiteState(ConstantState.CAR_SITE_STATE_INITIAL);
		car.setCarPledgeState(ConstantState.CAR_PLEDG_STATE_INITIAL);
		List<CarImage> images = JSON.parseArray(carImageJson, CarImage.class);
		if(images == null || images.size() == 0){
			return new ResultModel(ResultCode.RESULT_FAIL, "图片信息不能为空！");
		} else {
				for(CarImage image : images) {
					String fileId = "";
					try {
						fileId = fdfsClient.downloadAndUploadImg(image.getImageUrl());
						if(StringUtils.isEmpty(fileId) || fileId.equalsIgnoreCase("null")) {
							fileId = "";
						}
					} catch (Exception e) {
//						e.printStackTrace();
						logger.error("唐山市场录入车辆，下载图片异常", e);
					}
					image.setImageUrl(fileId);
				}
		}
		// 验证图片正确性
		if(!valiCarImage(images, car)) {
			return new ResultModel(ResultCode.RESULT_FAIL, "首图不能为空！");
		}
		car.setCarImages(images);
		car.setCarCreateTime(cDate);
		car.setCarStockTime(cDate);
		// 记录车辆日志
		CarLog carLog = new CarLog("唐山市场新增车源", new Date(), car.getUserId(), null);
		carLog.setCarStateKey("carStockState");
		carLog.setCarStateValue(ConstantState.CAR_STOCK_STATE_IN_ING);
		carLog.setCarLogSource(resource);
		List<CarLog> carLogs = new ArrayList<>();
		carLogs.add(carLog);
		car.setCarLogs(carLogs);
		carRpcService.insertCar(car);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "插入成功");
	}


	/**
	 * 验证图片正确性
	 * @param images
	 * @return
	 */
	private boolean valiCarImage(List<CarImage> images, Car car) {
		Map<String, CarImage> imageMap = new HashMap<>();
		boolean ok = false;
		for(CarImage cImage : images) {
			// 过滤url为空字符串的image
			if(StringUtils.isEmpty(cImage.getImageUrl())) {
				continue;
			}
			// 过滤重复Key
			if(imageMap.get(cImage.getImageKey()) != null) {
				continue;
			}
			imageMap.put(cImage.getImageKey(), cImage);
			if(!ok && cImage.getImageKey().equalsIgnoreCase("left_anterior") && StringUtils.isNotEmpty(cImage.getImageUrl())) {
				car.setCarImageUrl(cImage.getImageUrl());
				ok = true;
			}
		}
		// 清空当前list
		images.clear();
		// 过滤后的数据重新放到list中
		for(String key : imageMap.keySet()){
			images.add((imageMap.get(key)));
		}
		return ok;
	}

	/**
	 * 验证车架号是否存在
	 * @param vin
	 * @param carId
	 * @return
	 */
	private boolean valiCarVinExist(String vin, String carId){
		Car car = new Car();
		car.setCarVin(vin);
		//根据Vin查询车辆信息
		List<Car> cars = carRpcService.selectValiCarVin(car);
		if(cars != null && cars.size() > 0){
			if(StringUtils.isEmpty(carId)){
				// 新增车辆时vin码已存在
				return false;
			}else{
				for(Car carInfo:cars){
					if(carInfo.getCarId().equals(carId)){
						// 修改车辆时如果修改的是相同车辆返回true
						return true;
					}
				}
				return false;
			}
		}
		return true;
	}

	private String getClientIP(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
	}

	/**
	 * 新增商铺信息
	 * @param shop
	 * @return
	 */
	@RequestMapping(value = "/insertShopInfoCq", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel insertShopInfoCq(Shop shop, User user) {
		if(shop == null || user == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "商户信息不能为空！");
		}
//		if(StringUtils.isEmpty(user.getUserName())) {
//			return new ResultModel(ResultCode.RESULT_FAIL, "用户姓名不能为空！");
//		}
//		if(StringUtils.isEmpty(user.getUserMobile())) {
//			return new ResultModel(ResultCode.RESULT_FAIL, "用户联系方式不能为空！");
//		}
		if(StringUtils.isEmpty(shop.getMarketId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "市场ID不能为空！");
		}
		if(StringUtils.isEmpty(shop.getShopName())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "商户名称不能为空！");
		}
		if(StringUtils.isEmpty(shop.getShopMobile())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "商户联系方式不能为空！");
		}
		if(StringUtils.isEmpty(shop.getShopMappingId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "商户ID不能为空！");
		}
		shop.setShopId(null);
		shop.setShopState(1);
		Date cDate = new Date();
		shop.setShopCreateTime(cDate);
		shop.setShopUpdateTime(cDate);
//		user.setUserType(40);
//		user.setUserState(1);
//		user.setShop(shop);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "插入成功", shopRpcService.insertShop(shop));
	}

	/**
	 * 重庆新增车辆
	 * @param car
	 * @param carImageJson
	 * @return
	 */
	@RequestMapping(value = "/insertCarCq", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel insertCarCq(Car car, String carImageJson) {
		if(car == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆信息不能为空！");
		}
		if(car.getCarTitle() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆名称不能为空！");
		}
//		if(car.getBrandId() == null) {
//			return new ResultModel(ResultCode.RESULT_FAIL, "品牌不能为空！");
//		}
//		if(car.getSeriesId() == null) {
//			return new ResultModel(ResultCode.RESULT_FAIL, "车系不能为空！");
//		}
//		if(car.getModelId() == null) {
//			return new ResultModel(ResultCode.RESULT_FAIL, "车型不能为空！");
//		}
		if(StringUtils.isEmpty(car.getMarketId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "市场不能为空！");
		}
		if(StringUtils.isEmpty(car.getShopId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "店铺不能为空！");
		}
		if(StringUtils.isEmpty(car.getCarVin()) || car.getCarVin().length() != 17) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车驾号信息不正确（17位）！");
		}
		if(car.getCarRetailPrice() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "零售价不能为空(carRetailPrice)！");
		}
		if(car.getCarLicenceDate() == null) {
			car.setCarLicenceDate(getDate("1900-01-01", "yyyy-MM-dd"));
		}
		if(car.getCarValidateDate() == null) {
			car.setCarValidateDate(getDate("1900-01-01", "yyyy-MM-dd"));
		}
		if(car.getCarForceInsuranceDate() == null) {
			car.setCarForceInsuranceDate(getDate("1900-01-01", "yyyy-MM-dd"));
		}
		if(StringUtils.isEmpty(car.getMarketCarId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆ID不能为空！");
		}
		if(car.getCarCreateTime() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆创建时间不能为空！");
		}
		if(car.getCarSaleState() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "上架状态不能为空！");
		}
		if(car.getCarSaleState() != ConstantState.CAR_SALE_STATE_ONSALE_FINISH && 
				car.getCarSaleState() != ConstantState.CAR_SALE_STATE_OFFSALE){
			return new ResultModel(ResultCode.RESULT_FAIL, "上架状态错误！");
		}
		if(car.getCarSaleState() != ConstantState.CAR_SALE_STATE_OFFSALE){
			car.setCarSaleState(ConstantState.CAR_SALE_STATE_INITIAL);
		}
		if(car.getCarStockState() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "库存状态不能为空！");
		}
		if(car.getCarStockState() != ConstantState.CAR_STOCK_STATE_IN_FINISH &&
				car.getCarStockState() != ConstantState.CAR_STOCK_STATE_OUT_FINISH){
			return new ResultModel(ResultCode.RESULT_FAIL, "库存状态错误！");
		}
		if(car.getCarMileage() == null) {
			car.setCarMileage(new BigDecimal(0));
		}
		if(StringUtils.isEmpty(car.getCarOutColor())) {
			car.setCarOutColor("");
		}
		if(StringUtils.isEmpty(car.getCarInColor())) {
			car.setCarInColor("");
		}
		if(car.getCarNetworkPrice() == null) {
			car.setCarNetworkPrice(new BigDecimal(0));
		}
		//根据市场提供的marketShopId查询商铺信息
		Shop shop = new Shop();
		shop.setShopMappingId(car.getShopId());
		List<Shop> shops = shopRpcService.selectShopList(shop);
		if(shops == null || shops.size() == 0) {
			return new ResultModel(ResultCode.RESULT_FAIL, "商铺ID错误！");
		}
		shop = shops.get(0);
		car.setShopId(shop.getShopId());//查询到的shopId
		//查询用户信息
		User user = new User();
		user.setShopId(shop.getShopId());
		user.setUserType(40);
		List<User> users = userRpcService.selectUserList(user);
		if(users != null && users.size() > 0) {
			user = users.get(0);
			car.setUserId(user.getUserId());
		}else {
			car.setUserId("0");
		}
		car.setMarketId("142");
		car.setBrandId(0);
		car.setSeriesId(0);
		car.setModelId(0);
		car.setCarVin6(car.getCarVin().substring(11, 17));//截取后6位
		//初始化状态值
		car.setCarAuthState(ConstantState.CAR_AUTH_STATE_INITIAL);
		car.setCarDetectState(ConstantState.CAR_DETECT_STATE_INITIAL);
		car.setCarOrderState(0);
		List<CarImage> images = JSON.parseArray(carImageJson, CarImage.class);
		if(images != null) {
			for(CarImage image : images) {
				try {
					String fileId = fdfsClient.downloadAndUploadImg(image.getImageUrl());
					if(StringUtils.isEmpty(fileId) || fileId.equalsIgnoreCase("null")) {
						fileId = "";
					}
					image.setImageUrl(fileId);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		car.setCarImages(images);
		car = carRpcService.insertCar(car);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "插入成功", car);
	}

	/**
	 * 重庆销售信息
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/insertSaleBillCq", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel insertSaleBillCq(SaleBill saleBill, String provinceName, String cityName) {
		if(saleBill == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "单据信息不能为空！");
		}
		if(saleBill.getBillDate() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "开票日期不能为空！");
		}
		if(StringUtils.isEmpty(saleBill.getBillCode())) {
			saleBill.setBillCode("");
//			return new ResultModel(ResultCode.RESULT_FAIL, "发票代码不能为空！");
		}
		if(StringUtils.isEmpty(saleBill.getBillNo())) {
			saleBill.setBillNo("");
//			return new ResultModel(ResultCode.RESULT_FAIL, "发票号码不能为空！");
		}
		if(saleBill.getBillPrice() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "发票金额不能为空！");
		}else {
			BigDecimal zero = BigDecimal.valueOf(0);
			if (saleBill.getBillPrice().compareTo(zero) <= 0) {
				return new ResultModel(ResultCode.RESULT_FAIL, "发票金额不能小于等于0！");
			}
		}
		if(StringUtils.isEmpty(saleBill.getBillCarMark())) { 
			saleBill.setBillCarMark("");
//			return new ResultModel(ResultCode.RESULT_FAIL, "厂型不能为空！");
		}
		if(StringUtils.isEmpty(saleBill.getBillCarVin())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车架号不能为空！");
		}
		if(StringUtils.isEmpty(saleBill.getBillCarName())) {
			saleBill.setBillCarName("");
//			return new ResultModel(ResultCode.RESULT_FAIL, "车辆名称不能为空！");
		}
		if(StringUtils.isEmpty(saleBill.getBillCarPlateCode()) || saleBill.getBillCarPlateCode().length() != 7) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车牌号不正确！");
		}
		if(StringUtils.isEmpty(saleBill.getMarketId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "市场ID不能为空！");
		}
		if(StringUtils.isEmpty(saleBill.getShopId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "店铺ID不能为空！");
		}
//		if(StringUtils.isEmpty(saleBill.getUserId())) {
//			return new ResultModel(ResultCode.RESULT_FAIL, "用户信息不能为空！");
//		}
		if(StringUtils.isEmpty(provinceName)) {
			return new ResultModel(ResultCode.RESULT_FAIL, "省名称不能为空！");
		}
		if(StringUtils.isEmpty(cityName)) {
			return new ResultModel(ResultCode.RESULT_FAIL, "市名称不能为空！");
		}
		//根据市场提供的marketShopId查询商铺信息
		Shop shop = new Shop();
		shop.setShopMappingId(saleBill.getShopId());
		List<Shop> shops = shopRpcService.selectShopList(shop);
		if(shops == null || shops.size() == 0) {
			return new ResultModel(ResultCode.RESULT_FAIL, "商铺ID错误！");
		}
		shop = shops.get(0);
		saleBill.setShopId(shop.getShopId());//查询到的shopId
		//查询用户信息
		User user = new User();
		user.setShopId(shop.getShopId());
		user.setUserType(40);
		List<User> users = userRpcService.selectUserList(user);
		if(users != null && users.size() > 0) {
			user = users.get(0);
			saleBill.setUserId(user.getUserId());
		}else {
			saleBill.setUserId("0");
		}
		//根据市名称查询市信息
		City city = new City();
		city.setCityName(cityName);
		List<City> citys = cityRpcService.selectCityList(city);
		if(citys == null || citys.size() == 0) {
			return new ResultModel(ResultCode.RESULT_FAIL, "市名称错误！");
		}
		//根据省名称查询省信息
		Province province = new Province();
		province.setProvinceName(provinceName);
		List<Province> provinces = provinceRpcService.selectProvinceList(province);
		if(provinces == null || provinces.size() == 0) {
			return new ResultModel(ResultCode.RESULT_FAIL, "省名称错误！");
		}
		city = citys.get(0);
		province = provinces.get(0);
		String carPlateCode = saleBill.getBillCarPlateCode();
		saleBill.setBillCarPlateHead(carPlateCode.substring(0, 1));
		saleBill.setBillCarPlateMiddle(carPlateCode.substring(1, 2));
		saleBill.setBillCarPlateCode(carPlateCode.substring(2, 7));
		saleBill.setMarketId("142");
		saleBill.setBrandId(0);
		saleBill.setSeriesId(0);
		saleBill.setModelId(0);
		saleBill.setBillCarEngineNo("无");//发动机号不能为空
		saleBill.setCarTypeId(0);//车辆类型不能为空
		saleBill.setCityId(city.getCityId());
		saleBill.setProvinceId(province.getProvinceId());
		saleBill.setUserId("0");
		saleBill.setBillCreateTime(new Date());
		saleBillRpcService.insertSaleBill(saleBill);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "插入成功");
	}

	/**
	 * 修改车辆状态
	 * @param car
	 * @return
	 */
	@RequestMapping(value = "/updateCarState", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel updateCarState(Car car) {
		if(StringUtils.isEmpty(car.getMarketCarId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆ID不能为空！");
		}
		if(car.getCarSaleState() == null && car.getCarStockState() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "库存状态或销售状态不能为空");
		}
		if(car.getCarSaleState() != null && (car.getCarSaleState() != ConstantState.CAR_SALE_STATE_ONSALE_FINISH &&
				car.getCarSaleState() != ConstantState.CAR_SALE_STATE_OFFSALE)){
			return new ResultModel(ResultCode.RESULT_FAIL, "上架状态错误！");
		}
		if(car.getCarStockState() != null && (car.getCarStockState() != ConstantState.CAR_STOCK_STATE_IN_FINISH &&
				car.getCarStockState() != ConstantState.CAR_STOCK_STATE_OUT_FINISH)){
			return new ResultModel(ResultCode.RESULT_FAIL, "库存状态错误！");
		}
		Car carInfo = new Car();
		Car carWhere = new Car();
		carWhere.setMarketCarId(car.getMarketCarId());
		carInfo.setCarSaleState(car.getCarSaleState());
		carInfo.setCarStockState(car.getCarStockState());
		carRpcService.updateCar(carInfo, carWhere);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "修改成功");
	}

}
